package com.sxt.sys.controller;

import java.util.Date;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sxt.sys.service.LoginInforService;
import com.sxt.sys.utils.ActiverUser;
import com.sxt.sys.utils.WebUtils;
import com.sxt.sys.vo.LoginInforVo;
import com.sxt.sys.vo.UserVo;

@Controller
@RequestMapping("login")
public class LoginController {
	
	@Autowired
	private LoginInforService loginInforService;
	
	@RequestMapping("login")
	public String login(UserVo userVo,Model mode) {
		Subject subject = SecurityUtils.getSubject();
		//2,构造用户名和密码
		AuthenticationToken token=new  UsernamePasswordToken(userVo.getLoginname(),userVo.getPwd());
		try {
			//6,使用subject去执行认证
			subject.login(token);
			System.out.println("登陆成功");
			ActiverUser activerUser = (ActiverUser) subject.getPrincipal();
			WebUtils.getCurrentSession().setAttribute("user", activerUser.getUser());
			
			//登录时添加登录日志
			LoginInforVo loginInforVo = new LoginInforVo();
			loginInforVo.setLoginname(activerUser.getUser().getName()+"-" +activerUser.getUser().getLoginname());
			loginInforVo.setLoginip(WebUtils.getCurrentHttpServletRequest().getRemoteAddr());
			loginInforVo.setLogintime(new Date());
			System.out.println(WebUtils.getCurrentHttpServletRequest().getRemoteAddr());
			loginInforService.addLoginInfor(loginInforVo );
			return "index";
		} catch (IncorrectCredentialsException e) {
			System.out.println("密码不正确");
			mode.addAttribute("error", "密码不正确");
		}catch (UnknownAccountException e) {
			System.out.println("用户不存在");
			mode.addAttribute("error", "用户不存在");
		}
		return "login";
		
		
	}
	
	
	
	
}
